<template>
  <div class="admin-login-container">
    <el-card class="login-card">
      <h2>管理员登录</h2>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入管理员账号"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { loginApi } from '@/api/AdminApi'
import {useRouter} from "vue-router";


const loginFormRef = ref(null)

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [{ required: true, message: '请输入管理员账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const router = useRouter()
const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loginApi(loginForm.username, loginForm.password).then((result)=>{
        if(result.data.code==1){
          localStorage.removeItem("token")
          localStorage.setItem('token', result.data.data.token)
          localStorage.removeItem("user")
          ElMessage.success('登录成功')
          console.log("设置"+result.data)
          setTimeout(() => {
            router.push('/admin/manage')
          }, 1000);

        } else {
          ElMessage.error('账号或密码错误')
        }
      })



    }
  })
}
</script>

<style scoped>
.admin-login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  padding: 20px;
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
</style> 